<template>
  <div class="content_warp background_box">
    <headback :title="isDetail? t('shopDetail'):   (isEdit? t('editShop'):  t('applyShop')) " class="border_bottom"></headback>
    <div class="wrap topHead">
      <div class="form_center background_item light_border_shadow">
        <div class="form_item icon_uploader">
          <div class="form_title">{{ t('shopIcon') }}：</div>
          <van-uploader :after-read="afterReadIcon" name="shopIcon" :key="1111" :readonly="isDetail"
            :deletable="!isDetail" v-model="fileList" :max-count="1" />
        </div>
        <div class="form_item">
          <div class="form_title">{{ t('shopName') }}</div>：
          <div class="form_content">
            <van-field v-model="formData.name" :readonly="isDetail" :placeholder="t('pleaseEnterShopName')"
              input-align="right" />
          </div>
        </div>
        <div class="form_item">
          <div class="form_title">{{ t('contactInformation') }}</div>
          <div class="form_content">
            <van-field v-model="formData.phone" :readonly="isDetail" :placeholder="t('contactInformation')"
              input-align="right" />
          </div>
        </div>
        <div class="form_item">
          <div class="form_title">{{ t('tipRate') }}</div>
          <div class="form_content">
            <van-field v-model="formData.tipRate" type="number" :readonly="isDetail" :placeholder="t('tipRate')"
              input-align="right" >
              <template #button>% </template>
            </van-field>
          </div>
        </div>
        <div class="form_item">
          <div class="form_title">{{ t('shopRemark') }}</div>：
          <div class="form_content textArea_field">
            <van-field v-model="formData.describe"  type="textarea" rows="1" autosize 
              :placeholder="t('pleaseEnterShopRemark')" />
          </div>
        </div>
        <div class="form_item flex_column">
          <div class="form_title line_h30">{{ t('shopPictureOrVideo') }}</div>
          <van-uploader :preview-full-image="false" @click-preview="clickPreview" :after-read="afterRead"
            name="shopImgList" :readonly="isDetail" :key="2222" :deletable="!isDetail" 
            accept="image/*,video/*" v-model="fileList2" :multiple="isMultiple" :max-count="9">
            <template #preview-cover="{ file, url, type }">
              <div v-if="type == 'video'" class="preview-cover">
                <video muted :autoplay="false" class="video" :src="url"></video>
                <div class="video_controls">
                  <svg focusable="false" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                    <path
                      d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 14.5v-9l6 4.5-6 4.5z">
                    </path>
                  </svg>
                </div>
              </div>
            </template>
          </van-uploader>
        </div>

      </div>
      <div class="vollerList" v-if="cashPledge && !formData.account">
        <div> {{ t('addShopVoller') }} {{  cashPledge }} U 
          </div>
      </div>
      <van-button v-if="!isDetail" class="btn_shadow" style="margin-top: 10px;"  :loading="loading" @click="confirmShop(1)"
        type="primary"> {{   t('confirm') }} </van-button>
      <div v-if="!isDetail&&!isEdit" class="fixedD" style="margin-top: 10px;"> {{ t('myValue') }} ： {{ store.state.usdtBalance }} {{ store.state.USDT}}</div>

    </div>
  </div>
  <van-image-preview v-model:show="showFile" :startPosition="startPosition" :images="images">
    <template #image="{ src }">
      <van-image class="preview-cover" v-if="src.type == 'img'" :src="src.url" />
      <div v-if="src.type == 'video'&& showFile" class="preview-cover">
        <video muted :autoplay="true" class="video" :src="src.url" controls></video>
      </div>
    </template>
  </van-image-preview>
</template>
<script setup>
import { ethers } from "ethers";
import { useStore } from "vuex";
import { showToast } from "vant";
import { ref, reactive, onMounted, computed } from "vue";
import { useI18n } from "vue-i18n";
const { locale, t } = useI18n();

import { upload, jsonUpload, IPFS_PUBLIC_URL, getJson } from "@/api/User.js";
import { useRouter } from "vue-router";
import {usdtAbi} from "@/utils/abi/usdtAbi.js"
import userEth from "@/utils/userEth.js"
import loanEth  from "@/utils/loanEth.js"
import eth from  "@/utils/eth.js"
import { usdtContract, userContract } from "../../utils/config";
const cashPledge = computed(() => {
  return    (store.state.cashPledge)
})
const provider = new ethers.providers.Web3Provider(window.ethereum)
const router = useRouter();
const loading = ref(false)
const isMultiple = ref(false)
const store = useStore();
const showFile = ref(false)
const images = ref([])
const startPosition = ref(0)
const requireImg = (imgPath) => {
  return new URL(`../../assets/images/index/${imgPath}`, import.meta.url).href;
};
const  clickPreview = (...arg) => {
  startPosition.value = arg[1].index
  images.value = fileList2.value
  showFile.value = true
}
let formData = ref({
  name: "",
  describe: '',
  type: '',
  city: '',
  tipRate: (store.state.minFee*100) || '',
  cityId: '',
});
const isDetail = ref(false)
const isAudit = ref(false)
const isEdit = ref(false)
isDetail.value = router.currentRoute.value.query.isDetail ? true : false
isAudit.value = router.currentRoute.value.query.isAudit ? true : false
isEdit.value = router.currentRoute.value.query.isEdit ? true : false
const fileList = ref([]);
const fileList2 = ref([]);
let iconIpfsHash = ref("");
const approve = async (tokenContract,authContract,amount) => {
  const provider = new ethers.providers.Web3Provider(window.ethereum);
  const signer = await provider.getSigner();
  const Contract = new ethers.Contract(
    tokenContract,
    usdtAbi.contractAbi,
    provider
  );
  const ContractWithSinger = Contract.connect(signer);
  let hex = await ContractWithSinger.approve(authContract, amount);
  await hex.wait();
};
const getAllowance = async (contractAddress, authContract, decimals) => {
  const provider = new ethers.providers.Web3Provider(window.ethereum);
  const Contract = new ethers.Contract(
    contractAddress,
    usdtAbi.contractAbi,
    provider
  );
  let accounts = await provider.send("eth_requestAccounts", []);
  let address = accounts[0];
  let value = await Contract.allowance(address, authContract );
  return ethers.utils.formatUnits(value, decimals);
}
const confirmShop = async (type) => {
  try {
    let ContractWithSinger = userEth.ContractWithSinger
    if (!formData.value.name) {
      showToast(t('pleaseEnterShopName'));
      return
    }
    if (!formData.value.phone) {
      showToast(t('PleaseEnterContactInformation'));
      return
    }
    if(formData.value.tipRate < store.state.minFee*100){
      showToast("小费不能低于" + (store.state.minFee*10000/100) + '%')
      return
    }
    loading.value = true
    let imglist = []
    fileList2.value.forEach(res => {
      imglist.push({
        url: res.url.slice(res.url.indexOf('Qm')),
        type: res.type
      })
    })
    let params = {
      shopImg: imglist,
    }
    if (!iconIpfsHash.value) {
      showToast(t('pleaseUploadShopIcon'));
      loading.value = false
      return
    }
    formData.value.icon = iconIpfsHash.value
    let jsonData = await jsonUpload(params)
    formData.value.other = jsonData.data.IpfsHash

    
    // web3
    let data = [
      formData.value.name,
      formData.value.describe,
      formData.value.phone, //类型
      formData.value.icon || '', //货币
      formData.value.other,
      formData.value.tipRate*10000/100
    ]
    let hex = null
    if (isEdit.value) {
      data = [
      formData.value.icon || '', //货币
      formData.value.name,
      formData.value.phone, //类型
      formData.value.describe,
      formData.value.tipRate*10000/100,
      formData.value.other,
      ]
      hex = await ContractWithSinger.updateTraderInfo(...data)
    } else {
      // 新增
      if (store.state.cashPledge) {
        let tokenValue = await eth.getBalanceOf(
          usdtContract[0],
          usdtContract[3]
        );
      let needPay =  parseFloat((cashPledge.value*1.1).toFixed(4))
      if (tokenValue < needPay )  {
        showToast(t("noMoney"));
        loading.value = false
        return;
      }
      let allowance = await getAllowance(usdtContract[0],userContract, usdtContract[3]);
        if (Number(needPay) > Number(allowance)) {
          let amount = ethers.utils.parseUnits((needPay).toFixed(6), usdtContract[3])
          await approve(usdtContract[0], userContract,amount)
        }
      }
      try {
          hex = await ContractWithSinger.applyTrader(...data)
      } catch (error) {
        loading.value = false
        if(JSON.stringify(err)=='{}') {
        goToPage('index')
        setTimeout(()=>{
          window.location.reload()
        },300)
        } else {
          showToast(t('addShopFail'))
              goToPage('index')
        setTimeout(()=>{
          window.location.reload()
        },300)
        }
      }
    }
    await hex.wait()
    loading.value = false
    showToast(t('addShopSuccessful'))
    goToPage('index')
    setTimeout(()=>{
     window.location.reload()
    },300)
  } catch (err) {
    loading.value = false
    showToast(t('addShopFail'))
  }

}
const afterReadIcon = (file) => {
  file.status = 'uploading'
  upload(file.file)
    .then((res) => {
      iconIpfsHash.value = res.data.IpfsHash;
      fileList.value[0].url = IPFS_PUBLIC_URL + res.data.IpfsHash
      fileList.value[0].status = 'done'
      fileList.value[0].isImage = true
    })
    .catch((err) => {
      file.status = 'failed';
      file.message = t('uploadFail');
      iconIpfsHash.value = ''
      showToast(t('uploadFail'));
    });
};
const afterRead = (file) => {
  fileList2.value
  if (file instanceof Array) {
    file.forEach((item, index) => {
      item.status = 'uploading'
      let i = fileList2.value.length - file.length
      upload(item.file)
        .then((res) => {
          let obj = {
            status: 'done',
            url: IPFS_PUBLIC_URL + res.data.IpfsHash,
            isImage: true,
            type: item.file.type.startsWith('image') ? 'img' : (item.file.type.startsWith('video') ? 'video' : '')
          }
          fileList2.value[i + index] = { ...fileList2.value[i + index], ...obj }
        })
        .catch((err) => {
          item.status = 'failed';
          showToast(t('uploadFail'));
        });
    })
  } else {
    file.status = 'uploading'
    upload(file.file)
      .then((res) => {
        let obj = {
          status: 'done',
          url: IPFS_PUBLIC_URL + res.data.IpfsHash,
          isImage: true,
          type: file.file.type.startsWith('image') ? 'img' : (file.file.type.startsWith('video') ? 'video' : '')
        }
        fileList2.value[fileList2.value.length - 1] = { ...fileList2.value[fileList2.value.length - 1], ...obj }
      })
      .catch((err) => {
        file.status = 'failed';
        showToast(t('uploadFail'));
      });
  }
};
const getShopByDB = async (shopId) => {
  let shopItem = await orderEth.getShopById(shopId)
  iconIpfsHash.value = shopItem.image
  fileList.value = [{ url: shopItem.icon, isImage: true }]
  formData.value.name = shopItem.name
  formData.value.cityId = shopItem.cityId
  formData.value.city = shopItem.city
  formData.value.currency = shopItem.currency
  formData.value.currencyName = shopItem.symbol
}
const main = async () => {
  // 假如是店铺编辑  查询店铺 或者是详情
  if (router.currentRoute.value.query.tarder) {
    let account = router.currentRoute.value.query.tarder
    formData.value = await loanEth.getTraderItem(account)
    formData.value.tipRate = formData.value.tipRate*10000/100
    fileList.value = [{
      url:formData.value.url,
      isImage:true
    }]
    getJson(formData.value.other ).then((res) => {
      res.data.shopImg.forEach((e) => {
        if (e.url.indexOf('http') > -1) {
          e.url = IPFS_PUBLIC_URL + e.url.slice(e.url.indexOf('Qm'))
        } else {
          e.url = IPFS_PUBLIC_URL + e.url
        }
        e.isImage = true
      });
      fileList2.value = res.data.shopImg

    });
    iconIpfsHash.value = formData.value.url.slice(formData.value.url.indexOf('Qm'))

 
  }
};
main()
const goToPage = (value) => {
  router.push({
    name: value,
  });
};
</script>

<style lang="scss" scoped>
.textArea_field {
  .van-field {
    height: auto !important;
    line-height: 1.3 !important;
    font-size: 10px;
  }
}
.video_controls {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  height: 40px;
  width: 40px;
  fill: currentColor;
  color: #fff;
  opacity: 0.8;
}
.preview-cover {
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  text-align: center;
  position: relative;

  img {
    height: 100%;
    width: 100%;
  }

  .video {
    height: 100%;
      width: 100%;
      object-fit: cover;
  }
}
.BalanceList {
  margin-top: 10px;
  padding: 0.3rem 0.4rem;
  border-radius: 0.4rem;
}

.light_theme .textArea_field {
  margin-top: 5px;
  background: #f6f6f6;
  border-radius: 5px;
}

.dark_theme .textArea_field {
  margin-top: 5px;
  background: #303030;
  border-radius: 5px;
}

.vollerList {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 10px;
  color: #888;
}

.van-cell {
  font-size: 12px;
  background: transparent !important;
  word-break: break-word;
}

.content_warp {
  min-height: 100vh;
}

.wrap {
  padding: 10px 16px 20px 16px;
  box-sizing: border-box;
  position: relative;

  .van-button {
    margin-top: 0.58667rem;
    width: 100%;
    height: 32px;
    font-size: 0.32rem;
    font-weight: 500;
    border-radius: 0.53333rem;
  }

  .van-button--primary {
    border: none;
    font-size: 0.32rem;
    font-weight: 400;
  }

  .icon_uploader {
    :deep .van-uploader__upload {
      height: 40px;
      width: 40px;
    }

    :deep .van-uploader__preview-image {
      height: 40px;
      width: 40px;
    }

  }

  :deep .van-cell__right-icon {
    font-size: 12px;
  }



  .form_center {
    border-radius: 10px;
    padding: 10px 6px;

    .form_item {
      display: flex;
      padding: 0 0 0 10px;
      justify-content: space-between;
      align-items: center;

      .form_title {
        display: flex;
        align-items: center;
        opacity: 0.6;
        font-size: 12px;
        min-width: 54px;
      }

      .line_h30 {
        line-height: 30px;
      }

      .form_content {
        flex: 1;
      }

      .flex_right {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        padding-right: 15px;
        color: var(--van-cell-value-color);
        font-size: 12px;
      }

      .describe_detail {
        // padding-right: 15px;
        color: var(--van-cell-value-color);
        font-size: 12px;
      }
    }

    .flex_column {
      display: flex;
      flex-direction: column;
      align-items: flex-start;

      :deep .van-uploader__upload {
        height: 70px;
        width: 70px;
      }

      :deep .van-uploader__preview-image {
        height: 70px;
        width: 70px;
      }
    }
  }

  .two_button {
    display: flex;
    font-size: 12px;
    gap: 10px;
  }
}
</style>
